package top.ffhome.system.service.impl;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.stereotype.Service;
import top.ffhome.common.core.mybatisplus.service.impl.BaseServiceImpl;
import top.ffhome.system.domain.SysOperLog;
import top.ffhome.system.mapper.SysOperLogMapper;
import top.ffhome.system.service.ISysOperLogService;

import java.util.Arrays;
import java.util.Date;
import java.util.Map;

/**
 * 操作日志 服务层处理
 *
 * @author ruoyi
 */
@Service
public class SysOperLogServiceImpl extends BaseServiceImpl<SysOperLogMapper, SysOperLog> implements ISysOperLogService {
    @Override
    protected QueryWrapper<SysOperLog> generateWrapper(SysOperLog query) {
        Map<String, Object> params = query.getParams();
        return new QueryWrapper<SysOperLog>()
                .like(StrUtil.isNotBlank(query.getTitle()), "title", query.getTitle())
                .like(StrUtil.isNotBlank(query.getOperIp()), "oper_ip", query.getOperIp())
                .eq(query.getBusinessType() != null && query.getBusinessType() > 0,
                        "business_type", query.getBusinessType())
                .func(f -> {
                    if (ArrayUtil.isNotEmpty(query.getBusinessTypes())) {
                        f.in("business_type", Arrays.asList(query.getBusinessTypes()));
                    }
                })
                .eq(query.getStatus() != null && query.getStatus() > 0, "status", query.getStatus())
                .like(StrUtil.isNotBlank(query.getOperName()), "oper_name", query.getOperName())
                .apply(ObjectUtil.isNotEmpty(params.get("beginTime")),
                        "date_format(oper_time,'%y%m%d') >= date_format({0},'%y%m%d')",
                        params.get("beginTime"))
                .apply(ObjectUtil.isNotEmpty(params.get("endTime")),
                        "date_format(oper_time,'%y%m%d') <= date_format({0},'%y%m%d')",
                        params.get("endTime"))
                .orderByDesc("oper_id");
    }

    @Override
    protected void beforeInsert(SysOperLog entity) {
        entity.setOperTime(new Date());
        super.beforeInsert(entity);
    }

    @Override
    public void cleanOperLog() {
        mapper.cleanOperLog();
    }
}
